package com.example.bttrace;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;


public class MainActivity extends ActionBarActivity {
	public static final int timeout = 15000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ((TextView) findViewById(R.id.textView1)).setTextColor(Color.BLACK);
        Button scan= (Button)findViewById(R.id.button1);
        scan.setOnClickListener(new View.OnClickListener() {
             
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub  
                Intent intent = new Intent("com.google.zxing.client.android.SCAN");
                intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
                startActivityForResult(intent, 0);
            }
        });
        createTableHeader();
        (new RefreshTask()).execute();
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	
        int id = item.getItemId();
        
        if (id == R.id.action_settings)
        	startActivity(new Intent(this,SettingsActivity.class));
        
        if (id == R.id.action_refresh)
        	(new RefreshTask()).execute();
        
        return super.onOptionsItemSelected(item);
    } 
    
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (requestCode == 0) {
           if (resultCode == RESULT_OK) {
               
              String contents = intent.getStringExtra("SCAN_RESULT");
              (new CheckPointTask(contents)).execute();
              //Toast toast = Toast.makeText(getApplicationContext(), "Read: "+contents, Toast.LENGTH_SHORT);
              //toast.show();
              //String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
           
              // Handle successful scan
                                        
           } else if (resultCode == RESULT_CANCELED) {
        	   Toast toast = Toast.makeText(getApplicationContext(), "QRCode read cancelled", Toast.LENGTH_SHORT);
               toast.show();
           }
      }
   }
    
    private void createTableHeader (){
		android.widget.TableRow.LayoutParams p = new android.widget.TableRow.LayoutParams();
		p.rightMargin = MainActivity.dpToPixel(10,MainActivity.this);
		   	 
		TableLayout tableRacers = (TableLayout) findViewById(R.id.tableRacers);
		tableRacers.removeAllViewsInLayout();
		   	 
		TableRow header = new TableRow (MainActivity.this);
		   	 
		TextView h1 = new TextView(MainActivity.this);
		h1.setText("#");
		h1.setTextColor(Color.BLUE);
		h1.setTextSize(15);
		h1.setLayoutParams(p);
		header.addView(h1);
		
		TextView h2 = new TextView(MainActivity.this);
		h2.setText("Name");
		h2.setTextColor(Color.BLUE);
		h2.setTextSize(15);
		h2.setLayoutParams(p);
		header.addView(h2);
		
		TextView h3 = new TextView(MainActivity.this);
		h3.setText("Point 1");
		h3.setTextColor(Color.BLUE);
		h3.setTextSize(15);
		h3.setLayoutParams(p);
		header.addView(h3);
		
		TextView h4 = new TextView(MainActivity.this);
		h4.setText("Point 2");
		h4.setTextColor(Color.BLUE);
		h4.setTextSize(15);
		h4.setLayoutParams(p);
		header.addView(h4);
		
		TextView h5 = new TextView(MainActivity.this);
		h5.setText("Final Time");
		h5.setTextColor(Color.BLUE);
		h5.setTextSize(15);
		h5.setLayoutParams(p);
		header.addView(h5);
		
		tableRacers.addView(header);
		
		final View vline = new View(MainActivity.this);
		vline.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, 2));
		vline.setBackgroundColor(Color.BLUE);
		tableRacers.addView(vline);
    }
    
    private class RefreshTask extends AsyncTask<Void, Void, List<Racer>> {
    	private Socket client;
    	
    	public RefreshTask(){
    		client = new Socket();
    	}
    	
		@Override
		protected List<Racer> doInBackground(Void... params) {
			ArrayList<Racer> list = new ArrayList<Racer>(); 
			
			try {
	    		SharedPreferences sharedPref = getSharedPreferences(getString(R.string.preference_settings), Context.MODE_PRIVATE);
	    		int port = sharedPref.getInt(getString(R.string.saved_port), Settings.DEFAULT_PORT);
	    		String server = sharedPref.getString(getString(R.string.saved_ip), Settings.DEFAULT_IP);
	    		 
				client.connect(new InetSocketAddress(server, port), timeout);
				
				PrintWriter printwriter = new PrintWriter(client.getOutputStream(), true);
				printwriter.write("REFRESH\n");
				printwriter.flush();
				
				BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
				
				while (!br.readLine().equals("END")){
					String number = br.readLine();
					String name = br.readLine();
					String started = br.readLine();
					boolean start = started.equals("YES")? true : false;
					String time1 = br.readLine();
					String time2 = br.readLine();
					String time3 = br.readLine();
					Racer r = new Racer(number,name,start,time1,time2,time3);
					list.add(r);
				}
				
	    		printwriter.close();
	    		br.close();
				client.close(); 

			} 
			
	    	catch (SocketTimeoutException e) {
	    		list = null;
	    		Log.d("mytag", "Refresh - SocketTimeoutException: "+e.getMessage());
				e.printStackTrace();
			} 
			
	    	catch (UnknownHostException e) {
	    		list = null;
	    		Log.d("mytag", "Refresh - UnknownHostException: "+e.getMessage());
				e.printStackTrace();
			} 
	    	
	    	catch (IOException e) {
				list = null;
				Log.d("mytag", "Refresh - IOException: "+e.getMessage());
				e.printStackTrace();
			}
	    	
	    	return list;
		}
		
		@Override
	    protected void onCancelled() {
	        if(!client.isClosed())
	        	try {
	        		client.close();
	        	}
		        catch (IOException e) {
					e.printStackTrace();
				}
	    }
		
	    protected void onPostExecute(List<Racer> racers) {
	    	if (racers == null){
	    		Toast toast = Toast.makeText(getApplicationContext(), "Error connecting to server", Toast.LENGTH_SHORT);
	    		toast.show();
	    		return;
	    	}
    			    	
	    	android.widget.TableRow.LayoutParams p = new android.widget.TableRow.LayoutParams();
	 		p.rightMargin = MainActivity.dpToPixel(10,MainActivity.this);
	 		
	 		TableLayout tableRacers = (TableLayout) findViewById(R.id.tableRacers);
	 		
	 		for (int i=tableRacers.getChildCount()-1;i>1;i--)
	 			tableRacers.removeViewAt(i);
	    	 
            for (Racer racer : racers){
            	 TableRow row = new TableRow (MainActivity.this);
            	 
            	 TextView number = new TextView(MainActivity.this);
            	 number.setText(racer.getDorsal());
            	 number.setTextColor(Color.BLACK);
            	 number.setTextSize(15);
            	 number.setLayoutParams(p);
                 row.addView(number);
                 
                 TextView name = new TextView(MainActivity.this);
                 String txtName = racer.getName();
                 if (!racer.isStarted())
                	 txtName += "*";
                 name.setText(txtName);
                 name.setTextColor(Color.BLACK);
                 name.setTextSize(15);
                 name.setLayoutParams(p);
                 row.addView(name);
                 
                 TextView t1 = new TextView(MainActivity.this);
                 t1.setText(racer.getTime1());
            	 t1.setTextColor(Color.RED);
            	 t1.setTextSize(15);
            	 t1.setLayoutParams(p);
                 row.addView(t1);
                 
                 TextView t2 = new TextView(MainActivity.this);
                 t2.setText(racer.getTime2());
                 t2.setTextColor(Color.RED);
                 t2.setTextSize(15);
                 t2.setLayoutParams(p);
                 row.addView(t2);
                 
                 TextView t3 = new TextView(MainActivity.this);
                 t3.setText(racer.getTime3());
                 t3.setTextColor(Color.RED);
                 t3.setTextSize(15);
                 t3.setLayoutParams(p);
                 row.addView(t3);
                 
                 tableRacers.addView(row);
             }
            
            p = new android.widget.TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, 2);
    		p.topMargin = MainActivity.dpToPixel(20,MainActivity.this);
            
            View vline = new View(MainActivity.this);
    		vline.setLayoutParams(p);
    		vline.setBackgroundColor(Color.BLUE);
    		tableRacers.addView(vline);
    		
    		p = new android.widget.TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT);
    		p.topMargin = MainActivity.dpToPixel(40,MainActivity.this);
    		
    		TextView textAsterisk = new TextView(MainActivity.this);
    		textAsterisk.setLayoutParams(p);
    		textAsterisk.setText("Racers with * haven't started the race yet");
    		textAsterisk.setTextColor(Color.BLACK);
    		textAsterisk.setTextSize(12);
    		tableRacers.addView(textAsterisk);
             
	     }
	}
    
    
    private class CheckPointTask extends AsyncTask<Void, Void, String> {
    	private Socket client;
    	private String number;
    	
    	public CheckPointTask(String number){
    		client = new Socket();
    		this.number = number;
    	}
    	
    	@Override
		protected String doInBackground(Void... params) {
	    	String retMessage = "ERROR";
			
			try {
	    		SharedPreferences sharedPref = getSharedPreferences(getString(R.string.preference_settings), Context.MODE_PRIVATE);
	    		int port = sharedPref.getInt(getString(R.string.saved_port), Settings.DEFAULT_PORT);
	    		int checkPoint = sharedPref.getInt(getString(R.string.saved_checkpoint), Settings.DEFAULT_CHECKPOINT);
	    		String server = sharedPref.getString(getString(R.string.saved_ip), Settings.DEFAULT_IP);
	    		
	    		client.connect(new InetSocketAddress(server, port), timeout);
	    		    		
				PrintWriter printwriter = new PrintWriter(client.getOutputStream(), true);
				printwriter.write("CHECKPOINT\n");
				printwriter.write(checkPoint+"\n");
				printwriter.write(number+"\n");
				printwriter.flush();
				
				Log.d("mytag", "sent checkpoint");
				
				BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
				retMessage = br.readLine();
				
				printwriter.close();
	    		br.close();
				client.close();

			} 
	    	catch (SocketTimeoutException e) {
	    		Log.d("mytag", "CheckPoint - SocketTimeoutException: "+e.getMessage());
				e.printStackTrace();
				return "ERROR";
			} 
			
	    	catch (UnknownHostException e) {
	    		Log.d("mytag", "CheckPoint - UnknownHostException: "+e.getMessage());
				e.printStackTrace();
				return "ERROR";
			} 
	    	
	    	catch (IOException e) {
				Log.d("mytag", "CheckPoint - IOException: "+e.getMessage());
				e.printStackTrace();
				return "ERROR";
			}
	    	
	    	return retMessage;
		}
		
	    protected void onPostExecute(String message) {
	    	String toastMessage;
	    	boolean refresh = false;
	    	
	    	if(message.equals("ERROR"))
	    		toastMessage = "Error connecting to server. Please try again";
	    	else if (message.equals("OK")){
	    		toastMessage = "Racer checked in successfully";
	    		refresh = true;
	    	}
	    	else
	    		toastMessage = message;
	    		
	    	Toast toast = Toast.makeText(getApplicationContext(), toastMessage, Toast.LENGTH_SHORT);
	    	toast.show();
	    	
	    	if(refresh)
	    		(new RefreshTask()).execute();
	    }
	    
	    @Override
	    protected void onCancelled() {
	        if(!client.isClosed())
	        	try {
	        		client.close();
	        	}
		        catch (IOException e) {
					e.printStackTrace();
				}
	    }
	}   
    
    public static int dpToPixel(int dp, Context context) {
	     Float scale = context.getResources().getDisplayMetrics().density;
	     return (int) ((float) dp * scale);
	 }
}
